package com.sale.succ.system.txt;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import com.sale.succ.system.TradeMarketException;
import com.sale.succ.utils.Logger;
import com.sale.succ.utils.SystemConstants;
import com.sale.succ.utils.TraderConstants;
import com.sale.succ.utils.TraderHelper;

import eve.zipfile.ZipEntry;
import eve.zipfile.ZipException;
import eve.zipfile.ZipFile;
import eve.zipfile.ZipOutputStream;

public class TXTProcessing {
	private static final String CHARSET = "UTF8";
	private static final char DELIMITER = (char)0xb7;
	private static final byte[] buf = new byte[1024];
	
	public static ArrayList getCollectionFromTXT(String nameFile) {
		ArrayList retVal = new ArrayList();
		ZipBufferedReader reader = null;
		try {
			reader = getFileInputStream(nameFile);
	        String str;   
	        while((str = reader.readLine()) != null){
	        	if(!str.equals("")){
	        		ArrayList temp = new ArrayList();
		            StringTokenizer tok = new StringTokenizer(str,String.valueOf(DELIMITER));
		            while (tok.hasMoreTokens()){
		                String t = tok.nextToken().toString();
		                temp.add(t);
		            }
		            retVal.add(temp);
	        	}
	        }
		}
		catch (Exception ex) {
			new TradeMarketException(ex.getMessage(), TraderHelper.getLabel(TraderConstants.PROCESS_ABORTED));
		}
		finally{
			try {
				reader.close();
			} catch (Exception ex) {
				Logger.error(ex.getMessage());
			}
		}
		
		return retVal;
	}
	
	public static ArrayList getCollectionFromTXT(String nameFile, boolean f) {
		ArrayList retVal = new ArrayList();
		File file = new File(nameFile);
		if(file.exists()){
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(nameFile), CHARSET));
		        String str;   
		        while((str = reader.readLine()) != null){
		        	if(!str.equals("")){
		        		ArrayList temp = new ArrayList();
			            StringTokenizer tok = new StringTokenizer(str, String.valueOf(DELIMITER));
			            while (tok.hasMoreTokens()){
			                String t = tok.nextToken().toString();
			                temp.add(t);
			            }
			            retVal.add(temp);
		        	}
		        }
			}
			catch (Exception ex) {
				new TradeMarketException(ex.getMessage(), TraderHelper.getLabel(TraderConstants.PROCESS_ABORTED));
			}
			finally{
				try {
					reader.close();
				} catch (Exception ex) {
					Logger.error(ex.getMessage());
				}
			}
		}
		return retVal;
	}
	
	public static boolean getTXTFromCollection(ArrayList collection, String nameFile, boolean writeToEnd) {
		if(collection != null && collection.size() != 0){
			BufferedWriter writer = null;
			try {
				writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(nameFile, writeToEnd), CHARSET));
				for(int i=0; i<collection.size(); i++){
					ArrayList temp = (ArrayList)collection.get(i);
					String str = "";
					for(int j=0; j<temp.size(); j++){
						str += (String)temp.get(j);
						if(j < temp.size()-1){
							str += String.valueOf(DELIMITER);
						}
					}
					if(!str.equals("")){
						writer.write(str);
						writer.newLine();
					}
				}
			} catch (UnsupportedEncodingException e) {
				new TradeMarketException(e.getMessage(), TraderHelper.getLabel(TraderConstants.PROCESS_ABORTED));
			} catch (FileNotFoundException e) {
				new TradeMarketException(e.getMessage(), TraderHelper.getLabel(TraderConstants.PROCESS_ABORTED));
			} catch (Exception e) {
				new TradeMarketException(e.getMessage(), TraderHelper.getLabel(TraderConstants.PROCESS_ABORTED));
			}
			finally{
				try {
					writer.close();
				} catch (Exception ex) {
					Logger.error(ex.getMessage());
				}
			}
		}
		else{
			File file = new File(nameFile);
			if(file.exists()){
				if(!file.delete()) {
					Logger.info("File " + file.getName() + " can't be deleted !");
				}
				else {
					Logger.info("File " + file.getName() + " is deleted !");
				}
			}
		}
		return Boolean.TRUE;
	}
	
	private static ZipBufferedReader getFileInputStream(String nameFile) throws ZipException, IOException{
		ZipFile zip = new ZipFile(SystemConstants.FILES_IN_ZIP);
		ZipEntry entry = zip.getEntry(nameFile);
		return new ZipBufferedReader(zip, entry, CHARSET);
	}
	
	public static boolean createZip(String zipName, String dirName){
		ZipOutputStream out = null;
		try {
			File file = new File(dirName);
			if(file.isDirectory()){
				File [] fileList = file.listFiles(new FilterExtention("txt"));
				if(fileList.length > 0){
					out = new ZipOutputStream(new FileOutputStream(zipName));
					for(int i=0; i<fileList.length; i++){
						if(fileList[i].isFile()){
							FileInputStream in = null;
							try {
								in = new FileInputStream(fileList[i]); 
								out.putNextEntry(new ZipEntry(fileList[i].getName()));
								int len;
								while ((len = in.read(buf)) > 0){
									out.write(buf, 0, len);
								}
							}
							finally {
								out.closeEntry();
								in.close();
							}
						}
					}
				}
				else {
					return Boolean.FALSE;
				}
			}
			else {
				return Boolean.FALSE;
			}
		} catch (ZipException e) {
			new TradeMarketException(e.getMessage(), TraderHelper.getLabel(TraderConstants.PROCESS_ABORTED));
			return Boolean.FALSE;
		} catch (IOException e) {
			new TradeMarketException(e.getMessage(), TraderHelper.getLabel(TraderConstants.PROCESS_ABORTED));
			return Boolean.FALSE;
		}
		finally {
			try {
				out.close();
			} catch (Exception ex) {
				Logger.error(ex.getMessage());
				return Boolean.FALSE;
			}
		}
		return Boolean.TRUE;
	}
	
	public static void deleteOrderFiles(String dirName){
		File file = new File(dirName);
		if(file.isDirectory()){
			File [] fileList = file.listFiles(new FilterExtention("txt"));
			for(int i=0; i<fileList.length; i++){
				if(fileList[i].isFile()){
					boolean flag = fileList[i].delete();
					if(!flag) {
						Logger.info("File " + fileList[i].getName() + " can't be deleted !");
					}
					else {
						Logger.info("File " + fileList[i].getName() + " is deleted !");
					}
				}
			}
		}
	}
	
}
